/**
 * 
 */
package cn.edu.jlu.grid.vjm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

/**
 * @author whb
 *
 */
public class VJMPIJob {
	private static int id = 0;
	private final int ID = id++;
	private int resourceHandler = -1;
	private String executable = null;
	private int count = 0;
	private volatile int availableVJobsCnt = 0;
	
	public VJMPIJob(int n, String executable) {
		VJMCenter.getInstance().registerMPIJob(this);
		this.executable = executable;
		this.count = n;
	}
	
	public VJMPIJob(String rsl){}
	
	public void reserveResource() {
		Vector<Cluster> clusters = ResourceBroker.getAvailableClusters();
		new VJobDispatcher().dispatch(clusters, count);
		
		resourceHandler = VJMReservator.reserve(clusters);
	}
	
	public void request() {
		Vector<VJob> vjobs = getAllAvailableVJobs();
		String rsl = "+";
		for(int i = 0; i < vjobs.size(); i++) {
			rsl +=
				"\n(&(resourceManagerContact=\"" + vjobs.get(i).getGkContact() + "\")" + 
				"\n(executable=" + executable + ")" + 
				"\n(count=1)" +
				"\n(label=\"subjob " + i + "\")" +
				"\n(environment=(GLOBUS_DUROC_SUBJOB_INDEX " + i + ")" +
				"\n(LD_LIBRARY_PATH /opt/globus-4.0.8/lib))" +
				"\n(stdout=/tmp/" + i + ".out)" +
				"\n(stderr=/tmp/" + i + ".err))";
		}
		File tmpRslFile = null;
		try {
			tmpRslFile = File.createTempFile("tmpRsl", ".rsl", new File("/tmp"));
			System.out.println("temp rsl file: " + tmpRslFile.getPath());
			FileWriter fw = new FileWriter(tmpRslFile.getPath());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(rsl);
			bw.flush();
			bw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		try {
			Process p = Runtime.getRuntime().exec("globusrun -f  " + tmpRslFile.getPath());
			p.waitFor();
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			BufferedReader br = new BufferedReader(ir);
			String line;
			while((line = br.readLine()) != null) {
				System.out.println(line);
			}
			System.out.println("executable is submitted by duroc, returned :"
					+ p.exitValue());
			//TimeUnit.SECONDS.sleep(20);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tmpRslFile.delete();
	}
	
	public void waitForAllVjobsAvailable() {
		while(availableVJobsCnt != count);
	}
	public synchronized void notifyAvailable() {
		availableVJobsCnt++;
	}
	public int getResourceHandler() {
		return resourceHandler;
	}

	public Vector<VJob> getAllAvailableVJobs() {
		return VJobPool.getInstance().getAllAvailableVJobs(resourceHandler);
	}
	public int getID() {
		return ID;
	}
}
